<?php

/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/

namespace app\common\manager;
use app\common\constant\Constant;
use app\common\library\InviteCode;
use app\common\library\Wechat;
use app\common\model\AssistantOrder;
use app\common\model\Authentication;
use app\common\model\Config;
use app\common\model\Level;
use app\common\model\Order;
use app\common\model\Rebate;
use app\common\model\RelationImage;
use app\common\model\Store;
use app\common\model\Team;
use app\common\model\User;
use app\common\model\UserAccount;
use app\common\model\UserCoupon;
use app\common\model\UserFollow;
use app\common\model\UserTeam;
use think\Db;
use think\Exception;

class GroupManager extends BaseManager
{

     /**
     * 个人组队
     * @param User $user 用户信息
     * @param array $data 数据
     * @return void
     */
    public static function CaptainTeam(User $user,array $data,bool $trans=true):array
    {
        if ($trans)
            Db::startTrans();
        try {

            if (!$user->is_authentication){
                throw new Exception('您未实名认证，无法发起组队');
            }

            /*if (!$user->is_captain){
                throw new Exception('您不是队长，无法组队，请前往个人中心实名后申请入驻队长');
            }*/

            $levelInfo = Level::where('vl_id',$user->level)->find();
            if (!$levelInfo){
                throw new Exception('等级信息有误，无法发起组队');
            }

            $dayMaxTeamLimit = Config::where('name','day_max_team_limit')->value('value');
            $startTime = strtotime(date('Y-m-d 00:00:00',time()));
            $endTime = strtotime(date('Y-m-d 23:59:59',time()));
            $teamCount = Team::where('captain',$user->id)->where(['ct_date'=>['between',[$startTime,$endTime]]])->count();
            if ($teamCount >= intval($dayMaxTeamLimit)){
                throw new Exception('您今日组队数量已到最大数量，无法组队');
            }

            //if (!empty($data['is_store'])){

            if (!empty($data['store_id'])){
                $storeInfo = Store::where('id',$data['store_id'])->field('level,address,long,lat,province,city,district')->find();
                if (!$storeInfo){
                    throw new Exception('门店信息有误');
                }
                $data['province'] = $storeInfo['province'];
                $data['city'] = $storeInfo['city'];
                $data['district'] = $storeInfo['district'];
                $data['address'] = $storeInfo['address'];
                $data['long'] = $storeInfo['long'];
                $data['lat'] = $storeInfo['lat'];
                $invite = new InviteCode();
                $data['verification_code'] = $invite->enCode();

                $levelInfo = Level::where('vl_id',$storeInfo['level'])->find();
                if(!$levelInfo){
                    throw new Exception('门店等级信息有误');
                }
            }

            //}
            $data['level'] = $user->level;
            $data['start_date'] = strtotime($data['start_date']);
            $data['end_date'] = strtotime($data['end_date']);
            $data['cost'] = !empty($data['store_id']) ? $levelInfo['store_money'] : $levelInfo['store_false_money'];
            $data['basic_price'] = $levelInfo['basic_price'] ?? 0.00;
            $data['ct_date'] = time();
            $data['captain'] = $user->id;
            unset($data['is_store']);
            $image = $data['image'];
            unset($data['image']);
            //$teamInfo = Team::create($data);
            $teamModel = new Team();
            $id = $teamModel->insertGetId($data);
            if (empty($id)){
                throw new Exception('组队失败');
            }

            /**
             * 处理组队发布时的图片
             */
            $images = explode(',',$image);
            if (is_array($images) && count($images) > 0){
                foreach ($images as $v){
                    $imageInsert[] = [
                        'type' => RelationImage::TYPE_TEAM,
                        'relation_id' => $id,
                        'url' => $v,
                        'create_time' => time(),
                    ];
                }

                if ($imageInsert){
                    RelationImage::insertAll($imageInsert);
                }
            }
            if ($trans)
                Db::commit();

            $teamInfo = $teamModel->where('t_id',$id)->find()->toArray();
            $redis = new \Redis();
            $config = config('redis');
            $redis->pconnect($config['host'],$config['port']);
            if ($config['password']){
                $redis->auth($config['password']);
            }
            $redis->hSet(Constant::getHashAllTeamKey($config['prefix'],date('Ymd',$data['start_date'])),$id,json_encode(['start_date'=>$teamInfo['start_date'],'t_id'=>$teamInfo['t_id'],'end_date'=>$teamInfo['end_date'],'cost'=>$teamInfo['cost']]));
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
            self::setData(['id'=>$id]);
        }catch (Exception $exception){
            if ($trans)
                Db::rollback();
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }

        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
    }


    public static function CaptainTeamByStore(User $user,int $id,array $data,bool $trans=true):array
    {
        if ($trans)
            Db::startTrans();
        try {

            if (!$user->is_authentication){
                throw new Exception('您未实名认证，无法发起组队');
            }

            if (!$id){
                throw new Exception('未选择门店，无法发起组队');
            }

            $storeInfo = Store::where('id',$id)->find();
            if (!$storeInfo){
                throw new Exception('当前选择门店信息不全，无法发起组队');
            }

            $result = EmployeeManager::authCheck($user->id,$id,Team::IS_STORE_YES,null,EmployeeManager::TYPE_GROUP);
            if ($result['code'] != EmployeeManager::$successCode){
                throw new Exception($result['message']);
            }

            $levelInfo = Level::where('vl_id',$storeInfo['level'])->find();
            if (!$levelInfo){
                throw new Exception('等级信息有误，无法发起组队');
            }

            $data['is_store'] = Team::IS_STORE_YES;
            $data['address'] = $storeInfo['address'];
            $data['store_id'] = $id;
            $data['long'] = $storeInfo['long'];
            $data['lat'] = $storeInfo['lat'];
            $data['level'] = $storeInfo['level'];
            $data['start_date'] = strtotime($data['start_date']);
            $data['end_date'] = strtotime($data['end_date']);
            $data['cost'] =  $levelInfo['store_money'] ;
            $data['ct_date'] = time();
            $data['captain'] = $user->id;
            $data['release'] = Team::RELEASE_STATUS_SUCCESS;
            $data['pay_status'] = Team::PAY_STATUS_SUCCESS;
            $image = $data['image'];
            unset($data['image']);
            $teamModel = new Team();
            $id = $teamModel->insertGetId($data);
            if (empty($id)){
                throw new Exception('组队失败');
            }

            /**
             * 处理组队发布时的图片
             */
            $images = explode(',',$image);
            if (is_array($images) && count($images) > 0){
                foreach ($images as $v){
                    $imageInsert[] = [
                        'type' => RelationImage::TYPE_TEAM,
                        'relation_id' => $id,
                        'url' => $v,
                        'create_time' => time(),
                    ];
                }

                if ($imageInsert){
                    RelationImage::insertAll($imageInsert);
                }
            }
            if ($trans)
                Db::commit();

            $teamInfo = $teamModel->where('t_id',$id)->find()->toArray();
            $redis = new \Redis();
            $config = config('redis');
            $redis->pconnect($config['host'],$config['port']);
            if ($config['password']){
                $redis->auth($config['password']);
            }
            $redis->hSet(Constant::getHashAllTeamKey($config['prefix']),$id,json_encode(['start_date'=>$teamInfo['start_date'],'t_id'=>$teamInfo['t_id'],'end_date'=>$teamInfo['end_date'],'cost'=>$teamInfo['cost']]));
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
            self::setData(['id'=>$id]);
        }catch (Exception $exception){
            if ($trans)
                Db::rollback();
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage().$exception->getLine());
        }

        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
    }

    /**
     * 删除用户对应的组队信息
     * @param User $user
     * @param $id
     * @param bool $trans
     * @return array
     */
    public static function del(User $user,$id,bool $trans=true):array
    {
        if ($trans)
            Db::startTrans();
        try {
            $teamInfo = Team::where('t_id',$id)->where('delete',Team::DELETED_STATUS_NO)->find();
            if (!$teamInfo){
                throw new Exception('当前组队信息不存在');
            }

            $result = EmployeeManager::authCheck($user->id,$id,$teamInfo['is_store'],$teamInfo,EmployeeManager::TYPE_GROUP);
            if ($result['code']!=EmployeeManager::$successCode){
                throw new Exception($result['message']);
            }

            if(!\app\common\model\Team::where('t_id',$id)->update(['delete'=>\app\common\model\Team::DELETED_STATUS_SUCCESS,'up_date'=>time()])){
                throw new Exception('删除失败');
            }
            if ($trans)
                Db::commit();
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
        }catch (Exception $exception){
            if ($trans)
                Db::rollback();
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
    }

    /**
     * 取消组队
     * @param User $user
     * @param $id
     * @param bool $trans
     * @return array
     */
    public static function cancelGroup(User $user,$id,bool $trans=true):array
    {
        if ($trans)
            Db::startTrans();
        try {
            $teamModel = new \app\common\model\Team();
            $teamInfo = $teamModel->where('t_id',$id)->where('captain',$user->id)->find();
            if (!$teamInfo){
                throw new Exception('组队信息不存在');
            }

            if($teamInfo['end_date'] < time()){
                throw new Exception('当前组队已结束，无法取消');
            }

            if($teamInfo['confirm'] == Team::CONFIRM_YES){
                throw new Exception('当前组队已确认结束，无法取消');
            }

            $result = EmployeeManager::authCheck($user->id,$teamInfo['store_id'],$teamInfo['is_store'],$teamInfo,EmployeeManager::TYPE_GROUP);
            if ($result['code'] != EmployeeManager::$successCode){
                throw new Exception($result['message']);
            }

            if(!\app\common\model\Team::where('t_id',$id)->update(['release'=>\app\common\model\Team::RELEASE_STATUS_CANCEL,'up_date'=>time()])){
                throw new Exception('组队信息更新失败');
            }

            if ($teamInfo['pay_status'] == \app\common\model\Team::PAY_STATUS_SUCCESS){

                $userTeamModel = new UserTeam();
                $userTeamInfo = $userTeamModel->alias('ut')
                    ->join('pay_order po','po.po_id=ut.order_id','inner')
                    ->where('ut.team',$id)
                    ->where('ut.delete',UserTeam::DELETED_STATUS_NO)
                    ->where('ut.pay_state',UserTeam::PAY_STATUS_SUCCESS)
                    ->field('po.po_id,po.user_id,po.pay_state,po.order_money,po.assistant_ids,po.pay_date,po.user_coupon_id,po.real_money,ut.ut_id,ut.team,ut.state as utstate,ut.pay_state as utpaystate')
                    ->select();
                $orderModel = new Order();
                $wechat = new Wechat();
                if ($userTeamInfo){
                    $mobileArray = [];
                    foreach ($userTeamInfo as $v){
                        $openId = User::where('id',$v->user_id)->value('open_id');
                        /**
                         * 更新用户支付订单信息，进行退款至余额
                         */
                        if ($v->pay_state == Order::PAY_STATE_SUCCESS){
                            if(!$orderModel->where('po_id',$v->po_id)->where('pay_state',Order::PAY_STATE_SUCCESS)->update(['pay_state'=>Order::PAY_STATE_CANCEL,'cancel_date'=>time(),'up_date'=>time()])){
                                throw new Exception('成员支付订单更新失败');
                            }

                            if ($v->user_coupon_id){
                                if (!UserCoupon::where('id',$v->user_coupon_id)->where('user_id',$v->user_id)->where('status',UserCoupon::STATUS_USED)->update(['status'=>UserCoupon::STATUS_UNUSED,'update_time'=>time()])){
                                    throw new Exception('优惠券更新失败');
                                }
                            }

                            $result = UserAccountManager::money($v->user_id,$v->real_money,UserAccountManager::CHANGE_TYPE_INCOME,time(),UserAccountManager::TYPE_REFUND,['relation_id'=>$v->ut_id],false);
                            if($result['code']!=UserAccountManager::$successCode){
                                throw new Exception($result['message']);
                            }

                            $upgradeResult = UserAccountManager::LevelUpgrade($v->user_id,'downgrade',false);
                            if ($upgradeResult['code']!=UserAccountManager::$successCode){
                                throw new Exception($upgradeResult['message']);
                            }

                            if (!UserAccount::where('user_id',$v->user_id)->where('team_count',Db::raw('team_count >= 1'))->where('join_count',Db::raw('join_count >= 1'))->update(['team_count'=>Db::raw('team_count - 1'),'join_count'=>Db::raw('join_count - 1')])){
                                throw new Exception('用户信息更新失败');
                            }
                            $params['title'] = $teamInfo['title'] ?? '组队消息';
                            $params['date'] = date('Y-m-d H:i:s',$teamInfo['start_date']);
                            $params['address'] = $teamInfo['address'];
                            $params['reason'] = '参与人员不足取消';
                            $params['amount'] = $teamInfo['cost'];
                            //{"errcode":0,"errmsg":"ok","msgid":3522684900132012041}
                            $mobile = User::where('id',$v->user_id)->value('mobile');
                            if ($openId){
                                $result = $wechat->publishMsg($openId,$params,Wechat::TEMPLATE_ID_CANCEL,'page_main/views/teamDetails?id='.$id);
                                $resultArray = json_decode($result,true);
                                if ($resultArray['errcode']!=0){
                                    if ($mobile)
                                        $mobileArray[$v->user_id] = $mobile;
                                }
                            }else{
                                if ($mobile)
                                    $mobileArray[$v->user_id] = $mobile;

                            }

                            if ($v->assistant_ids){

                                \app\common\model\assistant\Order::where('order_id',$v->po_id)->where('orderer',$v->user_id)->where('status','<',\app\common\model\assistant\Order::STATUS_REFUND)->update(['status'=>\app\common\model\assistant\Order::STATUS_REFUND,'pay_status'=>\app\common\model\assistant\Order::PAY_STATUS_REFUND]);
                                AssistantOrder::where('order_id',$v->po_id)->where('user_id',$v->user_id)->where('status','<',AssistantOrder::STATUS_REFUND)->update(['status'=>AssistantOrder::STATUS_REFUND,'pay_status'=>AssistantOrder::PAY_STATUS_REFUND]);

                                $alisms = get_addon_config('alisms');
                                $teamName = $teamInfo['title'];
                                $assistantIds = explode(',',$v->assistant_ids);
                                foreach ($assistantIds as $assistantId) {
                                    $assistantInfo = User::where('assistant_id',$assistantId)->field('id,open_id,nickname,mobile')->find();
                                    if ($assistantInfo){
                                        $name = $assistantInfo['nickname'] ?? '';
                                        $mobile = $assistantInfo['mobile'] ?? '';
                                        if ($mobile){
                                            $result  = \app\common\library\Sms::notice($mobile,['name'=>$name,'teamName'=>$teamName],$alisms['template']['assistant']);
                                        }

                                        UserTeam::where('user_id',$assistantInfo['id'])->where('team',$id)->where('pay_state',UserTeam::PAY_STATUS_SUCCESS)->update(['pay_state'=>UserTeam::PAY_STATUS_REFUND,'is_system'=>UserTeam::SYSTEM_STATUS_YES,'up_date'=>time()]);
                                    }

                                }
                            }


                        }


                        /**
                         * 更新用户组队信息状态
                         */
                        if ($v->utpaystate == UserTeam::PAY_STATUS_SUCCESS && $v->utstate == UserTeam::STATE_SUCCESS) {
                            if (!UserTeam::where('ut_id',$v->ut_id)->where('pay_state',UserTeam::PAY_STATUS_SUCCESS)->update(['pay_state'=>UserTeam::PAY_STATUS_REFUND,'up_date'=>time()])){
                                throw new Exception('成员参加信息更新失败');
                            }
                        }

                    }

                    if ($mobileArray){
                        $alisms = get_addon_config('alisms');
                        $time = date('Y-m-d H:i:s',$teamInfo['start_date']);
                        $teamName = $teamInfo['title'];
                        foreach ($mobileArray as $mkey=>$mval){
                            $name = Authentication::where('user_id',$mkey)->value('real_name') ?? User::where('id',$mkey)->value('nickname');
                            $result  = \app\common\library\Sms::cancel($mval,['name'=>$name,'time'=>$time,'teamName'=>$teamName],$alisms['template']['cancel']);
                        }
                    }
                }
            }


            if ($trans)
                Db::commit();
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
        }catch (Exception $exception){
            if ($trans)
                Db::rollback();
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
    }

    /**
     * 系统自主取消组队
     * @param $id
     * @param bool $trans
     * @return array
     */
    public static function cancelGroupBySystem($id,bool $trans=true):array
    {
        if ($trans)
            Db::startTrans();
        try {

            $teamModel = new \app\common\model\Team();
            $teamInfo = $teamModel->where('t_id',$id)->find();
            if (!$teamInfo){
                throw new Exception('组队信息不存在');
            }
            $teamInfo = $teamInfo->toArray();
            if(!\app\common\model\Team::where('t_id',$id)->update(['release'=>\app\common\model\Team::RELEASE_STATUS_CANCEL,'is_system'=>\app\common\model\Team::SYSTEM_YES,'up_date'=>time()])){
                throw new Exception('组队信息更新失败');
            }
            if ($teamInfo['pay_status'] == \app\common\model\Team::PAY_STATUS_SUCCESS) {

                $userTeamModel = new UserTeam();
                $userTeamInfo = $userTeamModel->alias('ut')
                    ->join('pay_order po', 'po.po_id=ut.order_id', 'inner')
                    ->where('ut.team', $id)
                    ->where('ut.delete', UserTeam::DELETED_STATUS_NO)
                    ->where('ut.pay_state', UserTeam::PAY_STATUS_SUCCESS)
                    ->field('po.po_id,po.user_id,po.pay_state,po.order_money,po.pay_date,po.user_coupon_id,po.assistant_ids,po.real_money,ut.ut_id,ut.team,ut.state as utstate,ut.pay_state as utpaystate')
                    ->select();
                $orderModel = new Order();
                $wechat = new Wechat();

                if ($userTeamInfo) {
                    $mobileArray = [];
                    foreach ($userTeamInfo as $v) {
                        $openId = User::where('id',$v->user_id)->value('open_id');
                        /**
                         * 更新用户支付订单信息，进行退款至余额
                         */
                        if ($v->pay_state == Order::PAY_STATE_SUCCESS) {
                            if (!$orderModel->where('po_id', $v->po_id)->where('pay_state', Order::PAY_STATE_SUCCESS)->update(['pay_state' => Order::PAY_STATE_CANCEL, 'cancel_date' => time(), 'up_date' => time()])) {
                                throw new Exception('成员支付订单更新失败');
                            }

                            if ($v->user_coupon_id){
                                if (!UserCoupon::where('id',$v->user_coupon_id)->where('user_id',$v->user_id)->where('status',UserCoupon::STATUS_USED)->update(['status'=>UserCoupon::STATUS_UNUSED,'update_time'=>time()])){
                                    throw new Exception('用户优惠券更新失败');
                                }
                            }

                            $result = UserAccountManager::money($v->user_id, $v->real_money, UserAccountManager::CHANGE_TYPE_INCOME, time(), UserAccountManager::TYPE_REFUND, ['relation_id' => $v->ut_id], false);
                            if ($result['code'] != UserAccountManager::$successCode) {
                                throw new Exception($result['message']);
                            }

                            $upgradeResult = UserAccountManager::LevelUpgrade($v->user_id,'downgrade',false);
                            if ($upgradeResult['code']!=UserAccountManager::$successCode){
                                throw new Exception($upgradeResult['message']);
                            }

                            if (!UserAccount::where('user_id', $v->user_id)->where('team_count',Db::raw('team_count >= 1'))->where('join_count',Db::raw('join_count >= 1'))->update(['team_count' => Db::raw('team_count - 1'), 'join_count' => Db::raw('join_count - 1')])) {
                                throw new Exception('用户信息更新失败');
                            }

                            $params['title'] = $teamInfo['title'] ?? '组队消息';
                            $params['date'] = date('Y-m-d H:i:s',$teamInfo['start_date']);
                            $params['address'] = $teamInfo['address'];
                            $params['reason'] = '参与人员不足取消';
                            $params['amount'] = $teamInfo['cost'];
                            //{"errcode":0,"errmsg":"ok","msgid":3522684900132012041}
                            $mobile = User::where('id',$v->user_id)->value('mobile');
                            if ($openId){
                                $result = $wechat->publishMsg($openId,$params,Wechat::TEMPLATE_ID_CANCEL,config('wechat.team_invite_page').$id);
                                $resultArray = json_decode($result,true);
                                if ($resultArray['errcode']!=0){
                                    if ($mobile)
                                        $mobileArray[$v->user_id] = $mobile;
                                }
                            }else{
                                if ($mobile)
                                    $mobileArray[$v->user_id] = $mobile;

                            }
                        }


                        if ($v->assistant_ids){
                            \app\common\model\assistant\Order::where('order_id',$v->po_id)->where('orderer',$v->user_id)->where('status','<',\app\common\model\assistant\Order::STATUS_REFUND)->update(['status'=>\app\common\model\assistant\Order::STATUS_REFUND,'pay_status'=>\app\common\model\assistant\Order::PAY_STATUS_REFUND]);
                            AssistantOrder::where('order_id',$v->po_id)->where('user_id',$v->user_id)->where('status','<',AssistantOrder::STATUS_REFUND)->update(['status'=>AssistantOrder::STATUS_REFUND,'pay_status'=>AssistantOrder::PAY_STATUS_REFUND]);
                            $alisms = get_addon_config('alisms');
                            $teamName = $teamInfo['title'];
                            $assistantIds = explode(',',$v->assistant_ids);
                            foreach ($assistantIds as $assistantId) {
                                $assistantInfo = User::where('assistant_id',$assistantId)->field('id,open_id,nickname,mobile')->find();
                                if ($assistantInfo){
                                    $name = $assistantInfo['nickname'] ?? '';
                                    $mobile = $assistantInfo['mobile'] ?? '';
                                    if ($mobile){
                                        $result  = \app\common\library\Sms::notice($mobile,['name'=>$name,'teamName'=>$teamName],$alisms['template']['assistant']);
                                    }

                                    UserTeam::where('user_id',$assistantInfo['id'])->where('team',$id)->where('pay_state',UserTeam::PAY_STATUS_SUCCESS)->update(['pay_state'=>UserTeam::PAY_STATUS_REFUND,'is_system'=>UserTeam::SYSTEM_STATUS_YES,'up_date'=>time()]);
                                }

                            }
                        }
                        /**
                         * 更新用户组队信息状态
                         */
                        if ($v->utpaystate == UserTeam::PAY_STATUS_SUCCESS && $v->utstate == UserTeam::STATE_SUCCESS) {
                            if (!UserTeam::where('ut_id', $v->ut_id)->where('pay_state', UserTeam::PAY_STATUS_SUCCESS)->update(['pay_state' => UserTeam::PAY_STATUS_REFUND, 'is_system' => UserTeam::SYSTEM_STATUS_YES, 'up_date' => time()])) {
                                throw new Exception('成员参加信息更新失败');
                            }
                        }

                    }

                    if ($mobileArray){
                        $alisms = get_addon_config('alisms');
                        $time = date('Y-m-d H:i:s',$teamInfo['start_date']);
                        $teamName = $teamInfo['title'];
                        foreach ($mobileArray as $mkey=>$mval){
                            $name = Authentication::where('user_id',$mkey)->value('real_name') ?? User::where('id',$mkey)->value('nickname');
                            $result  = \app\common\library\Sms::cancel($mval,['name'=>$name,'time'=>$time,'teamName'=>$teamName],$alisms['template']['cancel']);
                        }
                    }
                }
            }

            if ($trans)
                Db::commit();
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);

        }catch (Exception $exception){
            if ($trans)
                Db::rollback();
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage().$exception->getLine());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];

    }

    /**
     * 用户个人取消组队参与
     * @param User $user
     * @param int $id
     * @param $trans
     * @return array
     */
    public static function cancelUserTeam(User $user,int $id,$trans=true):array
    {
        if ($trans)
            Db::startTrans();
        try {
            $userTeamModel = new UserTeam();
            $info = $userTeamModel->where('user_id',$user->id)->where('pay_state',UserTeam::PAY_STATUS_SUCCESS)->where('ut_id',$id)->find();
            if (!$info){
                throw new Exception('未找到报名记录，无法取消');
            }

            if ($info['state'] == UserTeam::STATE_WRITE_OFF){
                throw new Exception('当前报名记录已核销，无法取消');
            }

            if ($info['pay_state'] != UserTeam::PAY_STATUS_SUCCESS){
                throw new Exception('当前报名记录未支付或已取消，无法操作');
            }

            if(!UserTeam::where('ut_id',$id)->where('user_id',$user->id)->update(['pay_state'=>UserTeam::PAY_STATUS_REFUND,'up_date'=>time()])){
                throw new Exception('取消失败');
            }

            $orderModel = new Order();
            $orderInfo = $orderModel->where('po_id',$info['order_id'])->where('user_id',$info['user_id'])->where('type',Order::TYPE_TEAM)->where('relation_id',$info['team'])->where('pay_state',Order::PAY_STATE_SUCCESS)->find();
            if (!$orderInfo){
                throw new Exception('支付订单信息不存在，无法取消');
            }

            $teamInfo = Team::where('t_id',$info['team'])->find();
            if(
                !Order::where('po_id',$info['order_id'])
                    ->where('user_id',$info['user_id'])
                    ->where('type',Order::TYPE_TEAM)
                    ->where('relation_id',$info['team'])
                    ->where('pay_state',Order::PAY_STATE_SUCCESS)
                    ->update([
                        'pay_state'=>Order::PAY_STATE_CANCEL,
                        'cancel_date'=>time(),
                        'up_date'=>time()
                    ])
            ){
                throw new Exception('订单更新失败');
            }

            if (!Team::where('t_id',$info['team'])->where('join_number','>=','1')->where('ordered_number','>=','1')->update(['join_number'=>Db::raw('join_number -1'),'ordered_number'=>Db::raw('ordered_number -1'),'up_date'=>time()])) {
                throw new Exception('组队信息更新失败');
            }

            if ($orderInfo['user_coupon_id']){
                if (!UserCoupon::where('id',$orderInfo['user_coupon_id'])->where('user_id',$orderInfo['user_id'])->where('status',UserCoupon::STATUS_USED)->update(['status'=>UserCoupon::STATUS_UNUSED,'update_time'=>time()])){
                    throw new Exception('优惠券更新失败');
                }
            }

            $result = UserAccountManager::money($info['user_id'],$orderInfo['real_money'],UserAccountManager::CHANGE_TYPE_INCOME,time(),UserAccountManager::TYPE_REFUND,['relation_id'=>$info['ut_id']],false);
            if($result['code']!=UserAccountManager::$successCode){
                throw new Exception($result['message']);
            }


            $upgradeResult = UserAccountManager::LevelUpgrade($info['user_id'],'downgrade',false);
            if ($upgradeResult['code']!=UserAccountManager::$successCode){
                throw new Exception($upgradeResult['message']);
            }

            if (!UserAccount::where('user_id',$info['user_id'])->where('team_count',Db::raw('team_count >= 1'))->where('join_count',Db::raw('join_count >= 1'))->update(['team_count'=>Db::raw('team_count - 1'),'join_count'=>Db::raw('join_count - 1')])){
                throw new Exception('用户信息更新失败');
            }
//
//            if ($orderInfo['assistant_ids']){
//                $alisms = get_addon_config('alisms');
//                $teamName = $teamInfo['title'];
//                $assistantIds = explode(',',$orderInfo['assistant_ids']);
//                foreach ($assistantIds as $assistantId) {
//                    $assistantInfo = User::where('assistant_id',$assistantId)->field('id,open_id,nickname,mobile')->find();
//                    if ($assistantInfo){
//                        $name = $assistantInfo['nickname'] ?? '';
//                        $mobile = $assistantInfo['mobile'] ?? '';
//                        if ($mobile){
//                            $result  = \app\common\library\Sms::notice($mobile,['name'=>$name,'teamName'=>$teamName],$alisms['template']['assistant']);
//                        }
//
//                        UserTeam::where('user_id',$assistantInfo['id'])->where('team',$id)->where('pay_state',UserTeam::PAY_STATUS_SUCCESS)->update(['pay_state'=>UserTeam::PAY_STATUS_REFUND,'is_system'=>UserTeam::SYSTEM_STATUS_YES,'up_date'=>time()]);
//                    }
//
//                }
//            }
            $params['title'] = $teamInfo['title'] ?? '组队消息';
            $params['date'] = date('Y-m-d H:i:s',$teamInfo['start_date']);
            $params['address'] = $teamInfo['address'];
            $params['reason'] = '参与人员不足取消';
            $params['amount'] = $teamInfo['cost'];
            //{"errcode":0,"errmsg":"ok","msgid":3522684900132012041}
            $userInfo = User::where('id',$user->id)->field('mobile,open_id')->find();
            $wechat = new Wechat();
            if (!empty($userInfo['open_id'])){
                $result = $wechat->publishMsg($userInfo['open_id'],$params,Wechat::TEMPLATE_ID_CANCEL,'page_main/views/teamDetails?id='.$id);
                $resultArray = json_decode($result,true);
                if ($resultArray['errcode']!=0){
                    if ($userInfo['mobile']){
                        $alisms = get_addon_config('alisms');
                        $time = date('Y-m-d H:i:s',$teamInfo['start_date']);
                        $teamName = $teamInfo['title'];
                        $name = Authentication::where('user_id',$user->id)->value('real_name') ?? User::where('id',$user->id)->value('nickname');
                        $result  = \app\common\library\Sms::cancel($userInfo['mobile'],['name'=>$name,'time'=>$time,'teamName'=>$teamName],$alisms['template']['cancel']);
                    }

                }
            }else{
                if ($userInfo['mobile']){
                    $alisms = get_addon_config('alisms');
                    $time = date('Y-m-d H:i:s',$teamInfo['start_date']);
                    $teamName = $teamInfo['title'];
                    $name = Authentication::where('user_id',$user->id)->value('real_name') ?? User::where('id',$user->id)->value('nickname');
                    $result  = \app\common\library\Sms::cancel($userInfo['mobile'],['name'=>$name,'time'=>$time,'teamName'=>$teamName],$alisms['template']['cancel']);
                }

            }

            if ($trans)
                Db::commit();
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
        }catch (Exception $exception){
            if ($trans)
                Db::rollback();
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
    }
    /**
     * 组队更新
     * @param $id
     * @param $update
     * @param $isTrans
     * @return array
     */
    public static function modify($id,$update,$isTrans=true)
    {
        if ($isTrans)
            Db::startTrans();
        try {
            \app\common\model\Team::update($update,['t_id'=>$id]);
            if ($isTrans)
                Db::commit();
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
            self::setData(['id'=>$id]);
        }catch (Exception $e){
            if ($isTrans)
                Db::rollback();
            self::setStatusCode(self::$failCode);
            self::setMessage($e->getMessage());
        }

        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData() ];
    }


    /**
     * 特殊更新
     * @param $id
     * @param $isTrans
     * @return array
     */
    public static function specialModify($id,$isTrans=true)
    {
        if ($isTrans)
            Db::startTrans();
        try {
            $result = Team::where(['t_id'=>$id,'join_number'=>Db::Raw('join_number < number_people')])->update(['join_number'=>Db::raw('join_number+1')]);
            if (!$result){
                throw new Exception('当前组队已经满员');
            }
            if ($isTrans)
                Db::commit();
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
        }catch (Exception $e){
            if ($isTrans)
                Db::rollback();
            self::setStatusCode(self::$failCode);
            self::setMessage($e->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData() ];
    }
    /**
     * 详情
     * @param $id
     * @param $lng
     * @param $lat
     * @return array
     */
    public static function detail(User $user=null,$id,$lng,$lat)
    {
        try {
            if (!$lng || !$lat){
                throw new Exception('未获取到当前信息');
            }
            $teamModel = new \app\common\model\Team();
            $images = null;

            $info = $teamModel->where('t_id',$id)->fieldRaw('confirm,captain,verification_code,store_id,title,start_date,end_date,number_people,join_number,cost,level,`describe`,address,`release`,pay_status,type,ct_date,`long`,lat,(st_distance(point(`long`,lat),point('.$lng.','.$lat.'))*111195/1000 ) as juli')->find();
            if ($info){
                $image = RelationImage::where('relation_id',$id)->where('type',RelationImage::TYPE_TEAM)->select();
                if ($image){
                    $all = [];
                    foreach ($image as $value){
                        $all[] = $value['url'];
                    }
                    if ($all){
                        $images = implode(',',$all);
                        $info['image'] = $images;
                    }
                }

                if ($info['captain']){
                    $userModel = new User();
                    $captainInfo = $userModel->alias('u')->join('level l','u.level=l.vl_id','left')->where('u.id',$info['captain'])->field('u.id,u.level,u.nickname,u.avatar,l.vip_name,l.vip_icon')->find();
                    if (!empty($captainInfo['vip_icon']) && strrpos($captainInfo['vip_icon'],'http') === false){
                        $captainInfo['vip_icon'] = cdnurl($captainInfo['vip_icon']);
                    }
                    $info['captain_info'] = $captainInfo;
                }

                if (isset($user->id)){

                    if ($user->id == $info['captain']){
                        $info['ordered'] = $info['pay_status'] == \app\common\model\Team::PAY_STATUS_SUCCESS  ? 1 : 0 ;
                    }else{
                        $info['verification_code'] = '';
                        $info['ordered'] = (Order::where('user_id',$user->id)->where('relation_id',$id)->where('type',Order::TYPE_TEAM)->where('pay_state',Order::PAY_STATE_SUCCESS)->count() > 0 ? Order::PAY_STATE_SUCCESS : 0 );
                    }
                }else{
                    $info['verification_code'] = '';
                    $info['ordered'] = 0;
                }
            }

            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
            self::setData($info);
        }catch (Exception $e){
            self::setStatusCode(self::$failCode);
            self::setMessage($e->getMessage());
        }

        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData() ];
    }

    /**
     * 组队人员信息
     * @param User $user
     * @param $id
     * @param $page
     * @param $step
     * @return array
     */
    public static function teamJoiner(User $user=null,$id,$page=1,$step=10):array
    {
        $userId = 0;
        if (!empty($user->id)){
            $userId = $user->id;
        }

        $return = ['total'=>0,'totalPage'=>1,'currentPage'=>$page,'list'=>[]];
        try {
            $userTeamModel = new UserTeam();
            $count = $userTeamModel->alias('ut')
                ->join('user u','ut.user_id=u.id','inner')
                ->join('level l','u.level=l.vl_id','left')
                ->join('team_sign_up tsu','tsu.user_id=u.id and tsu.id=ut.sign_id','left')
                ->join('user_account ua','ua.user_id=u.id','inner')
                ->where('ut.team',$id)
                ->where('ut.delete',UserTeam::DELETED_STATUS_NO)
                ->where('ut.pay_state',UserTeam::PAY_STATUS_SUCCESS)
                ->count();

            $userTeamInfo = $userTeamModel->alias('ut')
                ->join('user u','ut.user_id=u.id','inner')
                ->join('level l','u.level=l.vl_id','left')
                ->join('team_sign_up tsu','tsu.user_id=u.id and tsu.id=ut.sign_id','left')
                ->join('user_account ua','ua.user_id=u.id','inner')
                ->where('ut.team',$id)
                ->where('ut.delete',UserTeam::DELETED_STATUS_NO)
                ->where('ut.pay_state',UserTeam::PAY_STATUS_SUCCESS)
                ->field('ut.team,ut.verif_code,ut.user_id,u.nickname,u.avatar,l.vip_name,l.vip_icon,ua.join_count,ua.team_count,ua.match_count,tsu.real_name,tsu.mobile,tsu.gender')->select();
            if ($userTeamInfo){
                foreach ($userTeamInfo as $key=>$value){
                    if ($userId){
                        $userTeamInfo[$key]['followed']  = UserFollow::where('fans_id',$userId)->where('user_id',$value['user_id'])->where('cancel',UserFollow::CANCEL_NO)->count() ? 1 : 0;
                    }else{
                        $userTeamInfo[$key]['followed']  = 0;
                    }
                    if (empty($value['avatar']) && strrpos($value['avatar'],'https')===false){
                        $userTeamInfo[$key]['avatar'] = cdnurl($value['avatar']);
                    }

                    if (empty($value['vip_icon']) && strrpos($value['vip_icon'],'https')===false){
                        $userTeamInfo[$key]['vip_icon'] = cdnurl($value['vip_icon']);
                    }
                }
            }
            $return['list'] = $userTeamInfo;
            $pageData = page($count,$step,$page);
            $data = array_merge($return,$pageData);
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
            self::setData($data);
        }catch (Exception $exception){
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData() ];
    }

    /**
     * 记录组队参与人员
     * @param $id
     * @param $data
     * @param $isTrans
     * @return array
     */
    public static function TeamJoinerInsert($id,$data,$isTrans=true)
    {
        if ($isTrans)
            Db::startTrans();
        try {
            $data['team'] = $id;
            $info = UserTeam::create($data);
            if (!$info){
                throw new Exception('组队人员信息插入失败');
            }
            if ($isTrans)
                Db::commit();
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
            self::setData($info);
        }catch (Exception $e){
            if ($isTrans)
                Db::rollback();
            self::setStatusCode(self::$failCode);
            self::setMessage($e->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData() ];
    }

    /**
     * 我的组队
     * @param User $user
     * @param $long
     * @param $lat
     * @param $type
     * @param $status
     * @param $page
     * @param $step
     * @return array
     */
    public static function teamInfoByUser(User $user,$long,$lat,$type=0,$status=0,$page=1,$step=10)
    {
        $return = ['total'=>0,'totalPage'=>1,'currentPage'=>$page,'list'=>[]];
        try {
            if ($page < 1){
                $page = 1;
            }

            $start = ($page-1)*$step;
            if ($type==1){
                $where['t.captain'] = $user->id;
                if ($status==1){
                    $where['t.pay_status'] = \app\common\model\Team::PAY_STATUS_INTI;
                    $where['t.release'] = ['<>',Team::RELEASE_STATUS_CANCEL];
                    $where['t.start_date'] = ['>',time()];
                }else if ($status==2){
                    $where['t.pay_status'] = \app\common\model\Team::PAY_STATUS_SUCCESS;
                    $where['t.release'] = ['<>',Team::RELEASE_STATUS_CANCEL];
                    $where['t.start_date'] = ['>',time()];
                }else if($status==3){
                    $where['t.pay_status'] = \app\common\model\Team::PAY_STATUS_SUCCESS;
                    $where['t.release'] = ['<>',Team::RELEASE_STATUS_CANCEL];
                    $where['t.number_people'] = Db::Raw('t.number_people = t.join_number');
                    $where['t.start_date'] = ['<',time()];
                    $where['t.end_date'] = ['>',time()];
                }else if($status==4){
                    $where['t.pay_status'] = \app\common\model\Team::PAY_STATUS_SUCCESS;
                    $where['t.release'] = ['<>',Team::RELEASE_STATUS_CANCEL];
                    $where['t.number_people'] = Db::Raw('t.number_people = t.join_number');
                    $where['t.end_date'] = ['<',time()];
                }else if($status==5){
                    $where['t.release'] = \app\common\model\Team::RELEASE_STATUS_CANCEL;
                }
                $teamModel = new \app\common\model\Team();
                $count = $teamModel->alias('t')
                    ->join('user u','t.captain=u.id','inner')
                    ->where($where)
                    ->where('t.delete',\app\common\model\Team::DELETED_STATUS_NO)
                    ->count();

                $info = $teamModel->alias('t')
                    ->join('user u','t.captain=u.id','inner')
                    ->where($where)
                    ->where('t.delete',\app\common\model\Team::DELETED_STATUS_NO)
                    ->field('t.t_id,t.title,t.captain,t.confirm,t.release,t.captain,t.number_people,t.cost,t.join_number,t.`describe`,t.pay_status,t.address,t.`long`,t.lat,t.ct_date,t.rule,t.start_date,t.end_date,(st_distance(point(t.`long`,t.lat),point('.$long.','.$lat.'))*111195/1000 ) as juli')
                    ->order('t.ct_date desc')
                    ->limit($start,$step)
                    ->select();


            }else{
                $where['ut.user_id'] = $user->id;
                $where['ut.delete'] = UserTeam::DELETED_STATUS_NO;
                $where['ut.user_ids'] = Db::Raw('ut.user_id!=t.captain');
                if ($status==2){
                    $where['t.release'] = ['<>',Team::RELEASE_STATUS_CANCEL];
                    $where['t.pay_status'] = \app\common\model\Team::PAY_STATUS_SUCCESS;
                    //$where['t.number_people'] = Db::Raw('t.number_people > t.join_number');
                    $where['t.start_date'] = ['>',time()];
                }else if($status==3){
                    $where['t.release'] = ['<>',Team::RELEASE_STATUS_CANCEL];
                    $where['t.pay_status'] = \app\common\model\Team::PAY_STATUS_SUCCESS;
                    $where['t.number_people'] = Db::Raw('t.number_people = t.join_number');
                    $where['t.start_date'] = ['<',time()];
                    $where['t.end_date'] = ['>',time()];
                }else if($status==4){
                    $where['t.release'] = ['<>',Team::RELEASE_STATUS_CANCEL];
                    $where['t.pay_status'] = \app\common\model\Team::PAY_STATUS_SUCCESS;
                    $where['t.number_people'] = Db::Raw('t.number_people = t.join_number');
                    $where['t.end_date'] = ['<',time()];
                }else if($status==5){
                    $where['t.release'] = \app\common\model\Team::RELEASE_STATUS_CANCEL;
                }

                $userTeamModel = new UserTeam();
                $count = $userTeamModel->alias('ut')
                    ->join('team t','t.t_id=ut.team','left')
                    ->join('user u','ut.user_id=u.id','inner')
                    ->where($where)
                    ->where('t.delete',\app\common\model\Team::DELETED_STATUS_NO)
                    ->count();

                $info = $userTeamModel->alias('ut')
                    ->join('team t','t.t_id=ut.team','left')
                    ->join('user u','ut.user_id=u.id','inner')
                    ->where($where)
                    ->where('t.delete',\app\common\model\Team::DELETED_STATUS_NO)
                    ->field('t.t_id,ut.ut_id,ut.pay_state,ut.state,t.title,t.confirm,t.captain,t.release,ut.user_id,t.number_people,t.cost,t.join_number,t.`describe`,t.pay_status,t.address,t.`long`,t.lat,t.ct_date,t.rule,t.start_date,t.end_date,(st_distance(point(t.`long`,t.lat),point('.$long.','.$lat.'))*111195/1000 ) as juli')
                    ->order('t.ct_date desc')
                    ->limit($start,$step)
                    ->select();
            }

            foreach ($info as $k=>&$v){
                $v['image'] = RelationImage::where('relation_id',$v['t_id'])->where('type',RelationImage::TYPE_TEAM)->select();
                if($v->release == \app\common\model\Team::RELEASE_STATUS_CANCEL){
                    $v['status_memo'] = '已取消';
                }else if ($v->pay_status==\app\common\model\Team::PAY_STATUS_INTI && $v->start_date > time()){
                    $v['status_memo'] = '待支付';
                }else if ($v->pay_status==\app\common\model\Team::PAY_STATUS_SUCCESS &&  $v->start_date > time()){
                    $v['status_memo'] = '未开始';
                }else if($v->pay_status == \app\common\model\Team::PAY_STATUS_SUCCESS && $v->number_people == $v->join_number && $v->start_date < time() && $v->end_date > time()){
                    $v['status_memo'] = '进行中';
                }else if ($v->pay_status == \app\common\model\Team::PAY_STATUS_SUCCESS && $v->end_date < time()){
                //}else if ($v->end_date < time()){
                    $v['status_memo'] = '已结束';
                }else{
                    $v['status_memo'] = '未知';
                }

                if (isset($v->state)){
                    if ($v->state == UserTeam::STATE_INIT){
                        $v['state_memo'] = '未报名';
                    }else if ($v->state==UserTeam::STATE_SUCCESS){
                        $v['state_memo'] = '已报名';
                    }else if ($v->state==UserTeam::STATE_WRITE_OFF){
                        $v['state_memo'] = '已核销';
                    }else if ($v->state==UserTeam::STATE_WRITE_OUT){
                        $v['state_memo'] = '已踢出';
                    }else{
                        $v['state_memo'] = '未知';
                    }
                }else{
                    $v['state_memo'] = '未知';
                }



                if (isset($v->pay_state)){

                    if ($v->pay_state == UserTeam::PAY_STATUS_INIT){
                        $v['pay_state_memo'] = '待支付';
                    }else if ($v->pay_state==UserTeam::PAY_STATUS_SUCCESS){
                        $v['pay_state_memo'] = '已支付';
                    }else if ($v->pay_state==UserTeam::PAY_STATUS_REFUND){
                        $v['pay_state_memo'] = '已退款';
                    }else{
                        $v['pay_state_memo'] = '未知';
                    }
                }else{
                    $v['pay_state_memo'] = '未知';
                }

            }
            $return['list'] = $info;
            $pageData = page($count,$step,$page);
            $data = array_merge($return,$pageData);
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
            self::setData($data);
        }catch (Exception $exception){
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData() ];
    }

    public static function getWriteOff(User $user,int $id):array
    {
        try {
            $userTeamModel = new UserTeam();
            $info = $userTeamModel->where(['team'=>$id,'user_id'=>$user->id])->where('state',UserTeam::STATE_SUCCESS)->find();
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
            self::setData($info);
        }catch (Exception $exception){
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData() ];
    }

    /**
     * 组队列表
     * @param int $level
     * @param  $lng
     * @param  $lat
     * @param int $radius
     * @param int $type
     * @param int $page
     * @param int $step
     * @return array
     */
    public static function TeamList(int $level=0, $lng=0.00, $lat=0.00,$radius=100,int $type=1,int $page=1,int $step=10):array
    {
        $return = ['total'=>0,'totalPage'=>1,'currentPage'=>$page,'list'=>[]];
        try {
            if ($type==1){
                $orderBy = 't.t_id desc';
            }else{
                $orderBy = 'juli asc';
            }

            if ($level){
                $where['t.level'] = $level;
            }
            $distance = null;
            if ($lng && $lat){
                $distance = getDistance($lat,$lng,$radius);
            }


            $where['t.release'] = Team::RELEASE_STATUS_SUCCESS;
            $where['t.end_date'] = ['>',time()];
            $start = ($page-1)*$step;
            $teamModel = new \app\common\model\Team();
            $count = $teamModel->alias('t')
                ->join('user u','t.captain=u.id','inner')
                ->join('merchant_store ms','ms.id=t.store_id','left')
                ->join('level l','l.vl_id=t.level','inner')
                ->where($where)
                ->where(function ($query) use($distance){
                    if ($distance){
                        if (!empty($distance['minLat']) && !empty($distance['maxLat']) && !empty($distance['minLng']) && !empty($distance['maxLng'])){
                            return $query->where('t.lat','between',[$distance['minLat'],$distance['maxLat']])
                                ->where('t.long','between',[$distance['minLng'],$distance['maxLng']]);
                        }
                    }
                })
                ->where('t.delete',\app\common\model\Team::DELETED_STATUS_NO)
                ->count();

            if ($distance){
                $field='t.t_id,t.title,t.captain,t.release,t.type,t.level,t.captain,t.number_people,t.cost,t.join_number,t.`describe`,t.pay_status,t.address as taddress,t.`long` as tlong,t.lat as tlat,t.ct_date,t.rule,t.start_date,t.end_date,(st_distance(point(t.`long`,t.lat),point('.$lng.','.$lat.'))*111195/1000 ) as juli,ms.store_name,ms.mobile,ms.address,ms.`long`,ms.`lat`,ms.background_image,ms.business_start_hours,ms.business_end_hours,ms.description,ms.level,u.username,u.nickname,l.vip_name,l.vip_icon,u.avatar';
            }else{
                $field='t.t_id,t.title,t.captain,t.release,t.type,t.level,t.captain,t.number_people,t.cost,t.join_number,t.`describe`,t.pay_status,t.address as taddress,t.`long` as tlong,t.lat as tlat,t.ct_date,t.rule,t.start_date,t.end_date,0.00 as juli,ms.store_name,ms.mobile,ms.address,ms.`long`,ms.`lat`,ms.background_image,ms.business_start_hours,ms.business_end_hours,ms.description,ms.level,u.username,u.nickname,l.vip_name,l.vip_icon,u.avatar';
            }

            $info = $teamModel->alias('t')
                ->join('user u','t.captain=u.id','inner')
                ->join('merchant_store ms','ms.id=t.store_id','left')
                ->join('level l','l.vl_id=t.level','inner')
                ->where($where)
                ->where(function ($query) use($distance){
                    if ($distance){
                        if (!empty($distance['minLat']) && !empty($distance['maxLat']) && !empty($distance['minLng']) && !empty($distance['maxLng'])){
                            return $query->where('t.lat','between',[$distance['minLat'],$distance['maxLat']])
                                ->where('t.long','between',[$distance['minLng'],$distance['maxLng']]);
                        }
                    }
                })
                ->where('t.delete',\app\common\model\Team::DELETED_STATUS_NO)
                ->field($field)
                ->order($orderBy)
                ->limit($start,$step)
                ->select();

            if($info){
                foreach ($info as $k=>$v){
                    $v['image'] = RelationImage::where('relation_id',$v['t_id'])->where('type',RelationImage::TYPE_TEAM)->select();

                    if ($v->background_image && strrpos($v->background_image,'http')===false){
                        $v->background_image = cdnurl($v->background_image);
                    }

                    if ($v->vip_icon && strrpos($v->vip_icon,'http')===false){
                        $v->vip_icon = cdnurl($v->vip_icon);
                    }
                }
            }
            $pageData = page($count,$step,$page);
            $return['list'] = $info;
            $return = array_merge($return,$pageData);
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
            self::setData($return);
        }catch (Exception $exception){
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData() ];
    }

    /**
     * 确认组队已结束
     * @param User $user
     * @param $id
     * @param $trans
     * @return array
     */
    public static function confirmGroup(User $user,$id,$trans=true):array
    {
        if ($trans)
            Db::startTrans();
        try {
            $result = RebateManager::Rebate($user,Rebate::TYPE_TEAM,$id);
            if ($result['code']!=RebateManager::$successCode){
                throw new Exception($result['message']);
            }
            if ($trans)
                Db::commit();
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
        }catch (Exception $exception){
            if ($trans)
                Db::rollback();
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData() ];
    }

    public static function storeTeamList($storeId,$status=0,$page=1,$step=10)
    {
        $return = ['total'=>0,'totalPage'=>1,'currentPage'=>$page,'list'=>[]];
        try {
            if ($page < 1){
                $page = 1;
            }

            $start = ($page-1)*$step;
            //$where['t.is_store'] = Team::IS_STORE_YES;
            $where['t.store_id'] = $storeId;
            /*$isSuperManger = 0;
            if (StoreInfo::where('merchant_id',$user->merchant_id)->where('user_id',$user->id)->where('store_id',$storeId)->count()){
                $where['t.store_id'] = $storeId;
            }*/
            if ($status==2){
                $where['t.pay_status'] = \app\common\model\Team::PAY_STATUS_SUCCESS;
                $where['t.release'] = ['<>',Team::RELEASE_STATUS_CANCEL];
                $where['t.start_date'] = ['>',time()];
            }else if($status==3){
                $where['t.pay_status'] = \app\common\model\Team::PAY_STATUS_SUCCESS;
                $where['t.release'] = ['<>',Team::RELEASE_STATUS_CANCEL];
                $where['t.number_people'] = Db::Raw('t.number_people = t.join_number');
                $where['t.start_date'] = ['<',time()];
                $where['t.end_date'] = ['>',time()];
            }else if($status==4){
                $where['t.pay_status'] = \app\common\model\Team::PAY_STATUS_SUCCESS;
                $where['t.release'] = ['<>',Team::RELEASE_STATUS_CANCEL];
                $where['t.number_people'] = Db::Raw('t.number_people = t.join_number');
                $where['t.end_date'] = ['<',time()];
            }else if($status==5){
                $where['t.release'] = \app\common\model\Team::RELEASE_STATUS_CANCEL;
            }
            $teamModel = new \app\common\model\Team();
            $count = $teamModel->alias('t')
                ->join('user u','t.captain=u.id','inner')
                ->where($where)
                ->where('t.delete',\app\common\model\Team::DELETED_STATUS_NO)
                ->count();

            $info = $teamModel->alias('t')
                ->join('user u','t.captain=u.id','inner')
                ->where($where)
                ->where('t.delete',\app\common\model\Team::DELETED_STATUS_NO)
                ->field('t.t_id,t.title,t.captain,t.is_store,t.store_id,t.status,t.confirm,t.release,t.captain,t.number_people,t.cost,t.join_number,t.`describe`,t.pay_status,t.address,t.`long`,t.lat,t.ct_date,t.rule,t.start_date,t.end_date')
                ->limit($start,$step)
                ->select();

            foreach ($info as $k=>&$v){
                $v['image'] = RelationImage::where('relation_id',$v['t_id'])->where('type',RelationImage::TYPE_TEAM)->select();
                if($v->release == \app\common\model\Team::RELEASE_STATUS_CANCEL){
                    $v['status_memo'] = '已取消';
                }else if ($v->pay_status==\app\common\model\Team::PAY_STATUS_INTI && $v->start_date > time()){
                    $v['status_memo'] = '待支付';
                }else if ($v->pay_status==\app\common\model\Team::PAY_STATUS_SUCCESS &&  $v->start_date > time()){
                    $v['status_memo'] = '未开始';
                }else if($v->pay_status == \app\common\model\Team::PAY_STATUS_SUCCESS && $v->number_people == $v->join_number && $v->start_date < time() && $v->end_date > time()){
                    $v['status_memo'] = '进行中';
                }else if ($v->pay_status == \app\common\model\Team::PAY_STATUS_SUCCESS && $v->end_date < time()){
                    //}else if ($v->end_date < time()){
                    $v['status_memo'] = '已结束';
                }else{
                    $v['status_memo'] = '未知';
                }

            }
            $return['list'] = $info;
            $pageData = page($count,$step,$page);
            $data = array_merge($return,$pageData);
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
            self::setData($data);
        }catch (Exception $exception){
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData() ];
    }


    /**
     * 普通用户获取门店组队信息
     * @param int $storeId
     * @param int $page
     * @param int $step
     * @return array
     */
    public static function storeTeamListByUser(int $storeId,int $page=1,int $step=10):array
    {
        $return = ['total'=>0,'totalPage'=>1,'currentPage'=>$page,'list'=>[]];
        try {
            if ($page < 1){
                $page = 1;
            }

            $start = ($page-1)*$step;
            $where['t.is_store'] = Team::IS_STORE_YES;
            $where['t.release'] = Team::RELEASE_STATUS_SUCCESS;
            $where['t.store_id'] = $storeId;
            $teamModel = new \app\common\model\Team();
            $count = $teamModel->alias('t')
                ->join('user u','t.captain=u.id','inner')
                ->where($where)
                ->where('t.delete',\app\common\model\Team::DELETED_STATUS_NO)
                ->count();

            $info = $teamModel->alias('t')
                ->join('user u','t.captain=u.id','inner')
                ->where($where)
                ->where('t.delete',\app\common\model\Team::DELETED_STATUS_NO)
                ->field('t.t_id,t.title,t.captain,t.confirm,t.release,t.captain,t.number_people,t.cost,t.join_number,t.`describe`,t.pay_status,t.address,t.`long`,t.lat,t.ct_date,t.rule,t.start_date,t.end_date')
                ->limit($start,$step)
                ->select();

            foreach ($info as $k=>&$v){
                $v['image'] = RelationImage::where('relation_id',$v['t_id'])->where('type',RelationImage::TYPE_TEAM)->select();
                if($v->release == \app\common\model\Team::RELEASE_STATUS_CANCEL){
                    $v['status_memo'] = '已取消';
                }else if ($v->pay_status==\app\common\model\Team::PAY_STATUS_INTI && $v->start_date > time()){
                    $v['status_memo'] = '待支付';
                }else if ($v->pay_status==\app\common\model\Team::PAY_STATUS_SUCCESS &&  $v->start_date > time()){
                    $v['status_memo'] = '未开始';
                }else if($v->pay_status == \app\common\model\Team::PAY_STATUS_SUCCESS && $v->number_people == $v->join_number && $v->start_date < time() && $v->end_date > time()){
                    $v['status_memo'] = '进行中';
                }else if ($v->pay_status == \app\common\model\Team::PAY_STATUS_SUCCESS && $v->end_date < time()){
                    //}else if ($v->end_date < time()){
                    $v['status_memo'] = '已结束';
                }else{
                    $v['status_memo'] = '未知';
                }

            }
            $return['list'] = $info;
            $pageData = page($count,$step,$page);
            $data = array_merge($return,$pageData);
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
            self::setData($data);
        }catch (Exception $exception){
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData() ];
    }

    /**
     * 门店核销组队
     * @param User $user
     * @param string $verification_code
     * @param $trans
     * @return array
     */
    public static function writeOff(User $user,string $verification_code,$trans=true):array{
        if ($trans)
            Db::startTrans();
        try {
            $teamInfo = Team::where('verification_code',$verification_code)->find();
            if (!$teamInfo){
                throw new Exception('组队信息不存在');
            }

            if ($teamInfo->status == Team::STATUS_WRITE_OFF){
                throw new Exception('该组队已核销');
            }

            $authResult = EmployeeManager::authCheck($user->id,$teamInfo['store_id'],Team::IS_STORE_YES,$teamInfo,EmployeeManager::TYPE_WRITE);
            if ($authResult['code'] != EmployeeManager::$successCode){
                throw new Exception($authResult['message']);
            }
            $teamInfo->status = Team::STATUS_WRITE_OFF;
            $teamInfo->up_date = time();
            $teamInfo->save();
            if ($trans)
                Db::commit();
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
        }catch (Exception $exception){
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData() ];
    }
}